package Filter;

use JIP::ToolSet; # load my commonly-used modules in a single import
use parent qw( Class::Base Class::Accessor::Fast );

# Perl modules
use IO::File;
use Carp qw( croak );
use Memoize qw( memoize );
use English qw( -no_match_vars );

# searcher custom modules
use OutputWriter::Filter;
use Filter::Utils qw( getFileType nameDecoder pathDecoder );
use Taxonomy qw( getAllTaxonomies );

__PACKAGE__->mk_ro_accessors( qw(
    hostId
    hostIp
    inputFile
    outputDir
    inputFileHandler
    isMemoizeEnabled
) );

sub init {
    my( $self, $config ) = @ARG;

    $self->{'hostId'} = $config->{'host_id'}
        or croak 'required parameter "host_id" not defined';

    $self->{'hostIp'} = $config->{'host_ip'}
        or croak 'required parameter "host_ip" not defined';

    $self->{'inputFile'} = $config->{'input_file'}
        or croak 'required parameter "input_file" not defined';

    $self->{'outputDir'} = $config->{'output_dir'}
        or croak 'required parameter "output_dir" not defined';

    $self->{'isMemoizeEnabled'} = $config->{'enable_cache'} || undef;

    $self->_makeInputHandle;

    # для каждого типа контента таксономии создаются файловые дескрипторы
    $self->_makeOutputHandlers;

    return $self;
}

sub filterLoop {
    my $self = shift;

    memoize('pathDecoder') if defined $self->isMemoizeEnabled;

    while ( defined( $ARG = $self->inputFileHandler->getline ) ) {
        chomp;

        if ( my( $name, $path, $size ) = m/^file<\*\|\*>(.+)<\*\|\*>(.+)<\*\|\*>(\d+)$/ ) {
            my $handlerName = _getHandlerName( getFileType( $name ) );

            $self->{ $handlerName }->saveFileMetadata(
                host_id => $self->hostId,
                name    => nameDecoder( $name ),
                path    => pathDecoder( $path ),
                size    => $size,
            );
        }
        elsif ( ( $path ) = m/^dir<\*\|\*>(.+)$/ ) {
            my( $dirName ) = $path =~ m|([^/]+)$|;

            my $handlerName = _getHandlerName('folders');

            $self->{ $handlerName }->saveDirMetadata(
                host_id => $self->hostId,
                name    => nameDecoder( $dirName ),
                path    => pathDecoder( $path ),
            );
        }
        else {
            warn "unexpected value: '". $ARG ."'";
        }
    }
}

sub _getOutputFileLocation {
    my( $self, $contentType ) = @ARG;

    my $fileName = 'ftp_'. $contentType .'_'. $self->hostIp .'.txt';

    return $self->outputDir .'/'. $fileName;
}

# $ARG[0] === $contentType
sub _getHandlerName { return 'output'. ucfirst( $ARG[0] ) }

sub _makeInputHandle {
    my $self = shift;

    $self->{'inputFileHandler'} = IO::File->new( $self->{'inputFile'}, 'r' )
        or croak 'cannot opent input file: '. $OS_ERROR;
}

sub _makeOutputHandlers {
    my $self = shift;

    foreach my $eachContentType ( getAllTaxonomies() ) {
        my $handlerName = _getHandlerName( $eachContentType );

        $self->{ $handlerName } = OutputWriter::Filter->new(
            output_file => $self->_getOutputFileLocation( $eachContentType )
        );

        $self->{ $handlerName }->binmode(':utf8');
    }
}

1;
